<?php

require_once(dirname(__FILE__) . '/../config/settings.inc.php');
require_once('config.php');
require_once('Mailer.class.php');
$dsn = sprintf('mysql:host=%s;dbname=%s', _DB_SERVER_, _DB_NAME_);
$db = new PDO($dsn, _DB_USER_, _DB_PASSWD_, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

if ($result = $db->query('SELECT `id_scheduler`, `email` FROM `ps_scheduler` WHERE `scheduled_at` LIKE("' . date('Y-m-d 00:00:00') . '") AND `is_send`=0 ORDER BY `email` ASC')->fetchAll(PDO::FETCH_ASSOC)) {
    foreach ($result as $k=>$r) {
        if (preg_match("/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/", trim($r['email']))) {
            try {
                $mailer = new Mailer($connection);
                $mailer->SetFrom($from);
                $mailer->Subject = $subject;
                $mailer->Body = file_get_contents(dirname(__FILE__).'/index.tpl');
                $mailer->AddAddress(trim($r['email']));
                $mailer->ClearReplyTos();
                if (!empty($reply_to)) {
                    $mailer->AddReplyTo($reply_to);
                }
                //$mailer->SetEmbedImages($images, $image_path);
                //$mailer->SetAttachments($attachments, $attachment_path);
                $mailer->Send($mailer);
                $db->exec('UPDATE `ps_scheduler` SET `is_send`=1 WHERE `id_scheduler`='.(int) $r['id_scheduler']);
                
                echo "Wyslano wiadomosc do " . (trim($r['email'])) . " (" . ($k + 1) . "/" . count($result) . ") \n";
            } catch (Exception $e) {
                echo $e->getMessage();
            }
        }
    }
}